﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.SessionState;
using DataObjects;
using System.Net;
using System.IO;
using Newtonsoft.Json;

namespace GT5RemoteMobile.Services
{
    /// <summary>
    /// Summary description for Handler1
    /// </summary>
    public class GetDrivers : IHttpHandler, IRequiresSessionState
    {
        public Profile psnUser;
        public List<Profile> friends;
        public RemoteRaceData currentRace;
        public List<RemoteRaceDriver> currentDrivers;
        public string jsessionId;

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "application/json";
            psnUser = (Profile)context.Session["psnUser"];
            friends = (List<Profile>)context.Session["friends"];
            currentRace = (RemoteRaceData)context.Session["currentRace"];
            currentDrivers = (List<RemoteRaceDriver>)context.Session["currentDrivers"];
            jsessionId = context.Session["jsessionid"].ToString();

            string psnIdToLookup = context.Request.QueryString["psnId"];

            if (currentDrivers == null)
                currentDrivers = new List<RemoteRaceDriver>();
            
            currentDrivers.AddRange(LookupDrivers(psnIdToLookup));
            
            if (context.Session["currentDrivers"] != null)
                context.Session.Remove("currentDrivers");
            context.Session.Add("currentDrivers", currentDrivers);
        }

        public List<RemoteRaceDriver> LookupDrivers(string psnId)
        {
            // hack to get a proper jsession id from gran-turismo.com
            HttpWebRequest profileRequest = WebRequest.Create(new Uri("https://us.gran-turismo.com/us/api/gt5/remoterace/")) as HttpWebRequest;
            //ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
#if(DEBUG)
            //profileRequest.Proxy = new WebProxy("localhost", 8888);
#endif
            profileRequest.Method = "POST";
            StreamWriter writer = new StreamWriter(profileRequest.GetRequestStream());

            writer.Write("job=" + (int)RemoteRaceJobType.GET_DRIVERLIST + "&online_id=" + psnId.Trim());
            writer.Close();
            profileRequest.CookieContainer = new CookieContainer();
            profileRequest.Headers.Add("Cookie", jsessionId);
            profileRequest.Accept = "text/javascript, text/html, application/xml, text/xml, */*";
            profileRequest.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";

            //foreach (string c in Request.Cookies)
            //{
            //    Cookie cookie = new Cookie(Request.Cookies[c].Name, Request.Cookies[c].Value, Request.Cookies[c].Path, Request.Cookies[c].Domain);
            //    profileRequest.CookieContainer.Add(cookie);
            //}
            using (HttpWebResponse response = profileRequest.GetResponse() as HttpWebResponse)
            {
                StreamReader reader = new StreamReader(response.GetResponseStream());
                string jsonData = reader.ReadToEnd();
                return JsonConvert.DeserializeObject<List<RemoteRaceDriver>>(jsonData);
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}